package com.ycy.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Jimmy.xi
 * @date 2019-05-15 17:48
 */
public final class JsonUtil {

    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    private static ObjectMapper mapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    public static <T> String objToString(T obj) {
        if (null == obj) {
            return "";
        }
        try {
            return obj instanceof String ? (String) obj : mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("obj parse to string exception", e);
            return "";
        }
    }

    public static <T> T jsonToObj(String jsonStr,Class<T> tClass)  {
        try {
            T obj = mapper.readValue(jsonStr, tClass);
            return obj;
        }
        catch(IOException e){
            logger.error("json parse to object exception", e);
            throw new RuntimeException("json parse to object exception");
        }
    }

    public static <T> T jsonToObj(String jsonStr, TypeReference<T> tClass)  {
        try {
            ObjectMapper mapper = new ObjectMapper();
            T obj = mapper.readValue(jsonStr, tClass);
            return obj;
        }
        catch(IOException e){
            logger.error("json parse to object exception", e);
            throw new RuntimeException("json parse to object exception");
        }
    }


}
